import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Broadcaster implements Runnable {
    /*
     * Threaded handling of messages queued to be broadcasted to a list of
     * client sockets. These are for example TALK messages.
     */
    private final ConcurrentLinkedQueue<String> bcastMsgQ;
    private final ConcurrentHashMap<String, ChatServer.ClientsData> clientList;

    public Broadcaster(
	    ConcurrentHashMap<String, ChatServer.ClientsData> clientList) {
	bcastMsgQ = new ConcurrentLinkedQueue<String>();
	this.clientList = clientList;
    }

    @Override
    public void run() {
	while (true) {
	    if (!bcastMsgQ.isEmpty()) {
		String bMsg = bcastMsgQ.poll();
		// poll a message from the queue. Then send it to each actively
		// chatting client in clientList.
		for (ChatServer.ClientsData cData : clientList.values()) {
		    try {
			if (cData.isActive()) {
			    cData.getSocket().getOutputStream()
				    .write(bMsg.getBytes("UTF-8"));
			}
		    } catch (Exception e) {
			// ignore dead sockets.
		    }
		}
	    }
	}
    }

    public void addMsg(String msg) {
	// add message to be broadcasted to all members of the chat.
	bcastMsgQ.add(msg);
    }
}